package com.wisdom.view;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.hisun.phone.core.voice.Log4Util;
import com.wisdom.MainActivity;
import org.sipdroid.sipua.R;
import com.wisdom.VoiceApplication;
import com.wisdom.bean.CallLogBean;
import com.wisdom.bean.ContactBean;
import com.wisdom.tools.CCPConfig;
import com.wisdom.ui.MenuHorizontalScrollView;
import com.wisdom.util.BaseIntentUtil;
import com.wisdom.view.adapter.HomeDialAdapter;
import com.wisdom.view.adapter.T9Adapter;
import com.wisdom.view.sms.MessageBoxList;
import com.wisdom.voip.CallOutActivity;
import com.wisdom.voip.VoiceHelper;

public class HomeDialActivity extends Activity implements OnClickListener{
	private MenuHorizontalScrollView scrollView;
	private AsyncQueryHandler asyncQuery;
	
	private HomeDialAdapter adapter;
	private ListView callLogList;
	
	private List<CallLogBean>list;
	
	private LinearLayout bohaopan;
	private LinearLayout keyboard_show_ll;
	private Button keyboard_show;
	private Button menuBtn;
	private Button phone_view;
	private Button delete;
	private Map<Integer,Integer>map=new HashMap<Integer,Integer>();
	private SoundPool spool;
	private AudioManager am=null;
	
	private VoiceApplication application;
	private ListView listView;
	private T9Adapter t9Adapter;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_dial_page);
		
		application = (VoiceApplication)getApplication();
		listView = (ListView) findViewById(R.id.contact_list);
		
		bohaopan = (LinearLayout) findViewById(R.id.bohaopan);
		keyboard_show_ll = (LinearLayout) findViewById(R.id.keyboard_show_ll);
		keyboard_show = (Button) findViewById(R.id.keyboard_show);
		callLogList = (ListView)findViewById(R.id.call_log_list);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());
		
		keyboard_show.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialPadShow();
			}
			
		});
		
		am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
		spool = new SoundPool(11, AudioManager.STREAM_SYSTEM, 5);
		map.put(0, spool.load(this, R.raw.dtmf0, 0));
		map.put(1, spool.load(this, R.raw.dtmf1, 0));
		map.put(2, spool.load(this, R.raw.dtmf2, 0));
		map.put(3, spool.load(this, R.raw.dtmf3, 0));
		map.put(4, spool.load(this, R.raw.dtmf4, 0));
		map.put(5, spool.load(this, R.raw.dtmf5, 0));
		map.put(6, spool.load(this, R.raw.dtmf6, 0));
		map.put(7, spool.load(this, R.raw.dtmf7, 0));
		map.put(8, spool.load(this, R.raw.dtmf8, 0));
		map.put(9, spool.load(this, R.raw.dtmf9, 0));
		map.put(11, spool.load(this, R.raw.dtmf11, 0));
		map.put(12, spool.load(this, R.raw.dtmf12, 0));
		
		phone_view=(Button)findViewById(R.id.phone_view);
		phone_view.setOnClickListener(this);
		phone_view.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(null == application.getContactBeanList() || application.getContactBeanList().size()<1 || "".equals(s.toString())){
					listView.setVisibility(View.INVISIBLE);
					callLogList.setVisibility(View.VISIBLE);
				}else{
					if(null == t9Adapter){
						t9Adapter = new T9Adapter(HomeDialActivity.this);
						t9Adapter.assignment(application.getContactBeanList());
//						TextView tv = new TextView(HomeDialActivity.this);
//						tv.setBackgroundResource(R.drawable.dial_input_bg2);
//						listView.addFooterView(tv);
						listView.setAdapter(t9Adapter);
						listView.setTextFilterEnabled(true);
						listView.setOnScrollListener(new OnScrollListener() {
							public void onScrollStateChanged(AbsListView view, int scrollState) {
								if(scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
									if(bohaopan.getVisibility() == View.VISIBLE){
										bohaopan.setVisibility(View.GONE);
										keyboard_show_ll.setVisibility(View.VISIBLE);
									}
								}
							}
							public void onScroll(AbsListView view, int firstVisibleItem,
									int visibleItemCount, int totalItemCount) {
							}
						});
					}else{
						callLogList.setVisibility(View.INVISIBLE);
						listView.setVisibility(View.VISIBLE);
						t9Adapter.getFilter().filter(s);
					}
				}
			}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			public void afterTextChanged(Editable s) {
			}
		});
		delete = (Button) findViewById(R.id.delete);
		delete.setOnClickListener(this);
		delete.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				phone_view.setText("");
				return false;
			}
		});
		for (int i = 0; i < 12; i++) {
			View v = findViewById(R.id.dialNum1 + i);
			v.setOnClickListener(this);
		}
		init();
		
		
		
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.dialNum0:
			if (phone_view.getText().length() < 12) {
				play(1);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum1:
			if (phone_view.getText().length() < 12) {
				play(1);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum2:
			if (phone_view.getText().length() < 12) {
				play(2);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum3:
			if (phone_view.getText().length() < 12) {
				play(3);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum4:
			if (phone_view.getText().length() < 12) {
				play(4);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum5:
			if (phone_view.getText().length() < 12) {
				play(5);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum6:
			if (phone_view.getText().length() < 12) {
				play(6);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum7:
			if (phone_view.getText().length() < 12) {
				play(7);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum8:
			if (phone_view.getText().length() < 12) {
				play(8);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum9:
			if (phone_view.getText().length() < 12) {
				play(9);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialx:
			if (phone_view.getText().length() < 12) {
				play(11);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialj:
			if (phone_view.getText().length() < 12) {
				play(12);
				input(v.getTag().toString());
			}
			break;
		case R.id.delete:
			delete();
			break;
		case R.id.phone_view:
			if (phone_view.getText().toString().length() >= 4) {
				call(phone_view.getText().toString());
			}
			break;
		default:
			break;
		}
	}
	private class MyAsyncQueryHandler extends AsyncQueryHandler{

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
			// TODO Auto-generated constructor stub
		}
		protected void onQueryComplete(int token,Object cookie,Cursor cursor){
			if(cursor!=null&&cursor.getCount()>0){
				list=new ArrayList<CallLogBean>();
				SimpleDateFormat sfd=new SimpleDateFormat("MM-dd hh:mm");
				Date date;
				cursor.moveToFirst();
				for(int i=0;i<cursor.getCount();i++){
					cursor.moveToPosition(i);
					date=new Date(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));
					String number=cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
					int type=cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
					String cachedName=cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
					int id=cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
					
					CallLogBean clb=new CallLogBean();
					clb.setId(id);
					clb.setNumber(number);
					clb.setName(cachedName);
					if(null==cachedName||"".equals(cachedName)){
						clb.setName(number);
					}
					clb.setType(type);
					clb.setDate(sfd.format(date));
					
					list.add(clb);
				}
				if(list.size()>0){
					setAdapter(list);
				}
			}
		}
		
	}
	private void init(){
		Uri uri = CallLog.Calls.CONTENT_URI;
		
		String[] projection = { 
				CallLog.Calls.DATE,
				CallLog.Calls.NUMBER,
				CallLog.Calls.TYPE,
				CallLog.Calls.CACHED_NAME,
				CallLog.Calls._ID
		}; // 查询的列
		asyncQuery.startQuery(0, null, uri, projection, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);  
	}
	private String[] lianxiren1 = new String[] { "网络直拨","网络回拨", "发送短信"};
	//private String[] lianxiren1 = new String[] { "网络直拨","网络回拨","拨打电话", "发送短信", "查看详细"};
	private void setAdapter(List<CallLogBean> list){
		adapter=new HomeDialAdapter(this,list);
		
		callLogList.setAdapter(adapter);
		callLogList.setOnScrollListener(new OnScrollListener(){

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				 
				
			}

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(scrollState==OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
					//滚动不自动隐藏拨号盘了，怕很多用户不会打开拨号盘
//					if(bohaopan.getVisibility()==View.VISIBLE){
//						bohaopan.setVisibility(View.GONE);
//						keyboard_show_ll.setVisibility(View.VISIBLE);
//					}
				}
				
			}
			
		});
		callLogList.setOnItemClickListener(new  OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				CallLogBean clb = (CallLogBean) adapter.getItem(position);
				showContactDialog(lianxiren1, clb, position);
			}});
	}	
	private String getSMSThreadId(String adddress){
		Cursor cursor = null;  
		ContentResolver contentResolver = getContentResolver();  
		cursor = contentResolver.query(Uri.parse("content://sms"), SMS_COLUMNS, " address like '%" + adddress + "%' ", null, null);  
		String threadId = "";
		if (cursor == null || cursor.getCount() > 0){
			cursor.moveToFirst();
			threadId = cursor.getString(0);
			cursor.close();
			return threadId;
		}else{
			cursor.close();
			return threadId;
		}
	}
	public static String[] SMS_COLUMNS = new String[]{  
		"thread_id"
	};
	private void showContactDialog(final String[] arg ,final CallLogBean cb, final int position){
		call(cb.getNumber());
//		new AlertDialog.Builder(this).setTitle(cb.getName()).setItems(arg,
//				new DialogInterface.OnClickListener(){
//			public void onClick(DialogInterface dialog, int which){
//
//				Uri uri = null;
//				String toPhone = cb.getNumber();
//				String threadId = getSMSThreadId(cb.getNumber());
//				Map<String, String> map = new HashMap<String, String>();
//				Intent it=null;
//				switch(which){
//				case 0://网络直拨
//					if(!checkLogin())return;
//					startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK,toPhone);
//					break;
//				case 1://网络回拨
//
//					if(!checkLogin())return;
//					startVoipCall(VOIP_CALL_TYPE_BACK_TALK,toPhone);
//					break;
////				case 2://打电话
////					toPhone = cb.getNumber();
////					uri = Uri.parse("tel:" + toPhone);
////					it = new Intent(Intent.ACTION_CALL, uri);
////					startActivity(it);
////					break;
//
//				case 2://发短息
//
//					threadId = getSMSThreadId(cb.getNumber());
//					
//					map = new HashMap<String, String>();
//					map.put("phoneNumber", cb.getNumber());
//					map.put("threadId", threadId);
//					BaseIntentUtil.intentSysDefault(HomeDialActivity.this, MessageBoxList.class, map);
//					break;
//
//				case 4:// 查看详细       修改联系人资料
//
//					uri = ContactsContract.Contacts.CONTENT_URI;
//					Uri personUri = ContentUris.withAppendedId(uri, cb.getId());
//					Intent intent2 = new Intent();
//					intent2.setAction(Intent.ACTION_VIEW);
//					intent2.setData(personUri);
//					startActivity(intent2);
//					break;
//
//	
//			}}
//		}).show();
	}
	Boolean checkLogin(){
		if(!CCPConfig.check()){
			Toast.makeText(HomeDialActivity.this, "请先注册或者登录！.", Toast.LENGTH_SHORT).show();
			startActivity(new Intent(HomeDialActivity.this,WelcomeActivity.class));
			return false;
		}
		return true;
		
	}
	public void dialPadShow(){
		if(bohaopan.getVisibility() == View.VISIBLE){
			bohaopan.setVisibility(View.GONE);
			keyboard_show_ll.setVisibility(View.VISIBLE);
		}else{
			bohaopan.setVisibility(View.VISIBLE);
			keyboard_show_ll.setVisibility(View.INVISIBLE);
		}
	}
	private void play(int id) {
		int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int current = am.getStreamVolume(AudioManager.STREAM_MUSIC);

		float value = (float)0.7 / max * current;
		spool.setVolume(spool.play(id, value, value, 0, 0, 1f), value, value);
	}
	private void input(String str) {
		String p = phone_view.getText().toString();
		phone_view.setText(p + str);
	}
	private void delete() {
		String p = phone_view.getText().toString();
		if(p.length()>0){
			phone_view.setText(p.substring(0, p.length()-1));
		}
	}
	private void call(final String phone) {
		//Uri uri = Uri.parse("tel:" + phone);
		//Intent it = new Intent(Intent.ACTION_CALL, uri);
		//startActivity(it);
		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if(CCPConfig.CallSetting.equals("1")){
			//直接回拨
			startVoipCall(VOIP_CALL_TYPE_BACK_TALK,phone);
			return;
		}
		if(CCPConfig.CallSetting.equals("2")){
			//直接直拨
			startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK,phone);
			return;
		}
		if(wifi==State.CONNECTED||wifi==State.CONNECTING){
			//直拨
			startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK,phone);
			return;
		}else{
			startVoipCall(VOIP_CALL_TYPE_BACK_TALK,phone);
			return;
			//回拨
		}
         
//		new AlertDialog.Builder(this).setTitle(phone).setItems(new String[]{"网络直拨","网络回拨","发短信"},
//				new DialogInterface.OnClickListener(){
//			public void onClick(DialogInterface dialog, int which){
//					
//				Uri uri = null;
//				String threadId = getSMSThreadId(phone);
//				Map<String, String> map = new HashMap<String, String>();
//				switch(which){
//				case 0://网络直拨
//					startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK,phone);
//					break;
//
////				case 2://打电话
////
////					String threadId = getSMSThreadId(phone);
////					
////					Map<String, String> map = new HashMap<String, String>();
////					map.put("phoneNumber", phone);
////					map.put("threadId", threadId);
////					BaseIntentUtil.intentSysDefault(HomeDialActivity.this, MessageBoxList.class, map);
////					break;
//				case 1://网络回拨
//					startVoipCall(VOIP_CALL_TYPE_BACK_TALK,phone);
//					break;
//
//				case 2://发短息
//
//					threadId = getSMSThreadId(phone);
//					
//					map = new HashMap<String, String>();
//					map.put("phoneNumber", phone);
//					map.put("threadId", threadId);
//					BaseIntentUtil.intentSysDefault(HomeDialActivity.this, MessageBoxList.class, map);
//					break;
//	
//			}}
//		}).show();
	}
	private static final int VOIP_CALL_TYPE_BACK_TALK = 203;
	private static final int VOIP_CALL_TYPE_DIRECT_TALK = 204;
	void startVoipCall(int mCallType,String phoneStr){
		
		
		if(TextUtils.isEmpty(phoneStr)){
			VoiceApplication.getInstance().showToast(R.string.edit_input_empty);
			return;
		}
		tyoe=mCallType;
		phoneto=phoneStr;
		Intent intent=new Intent(this,CallOutActivity.class);
		//直播电话
		if(!phoneStr.startsWith("0")&&!phoneStr.startsWith("1")){
			//判断输入合法性
			VoiceApplication.getInstance().showToast(getString(R.string.network_dial_number_format));
			return;
		}
		intent.putExtra(VoiceApplication.VALUE_DIAL_VOIP_INPUT,phoneStr);
		intent.putExtra(VoiceApplication.VALUE_DIAL_MODE,VoiceApplication.VALUE_DIAL_MODE_DIRECT);
		startActivity(intent);
		/*VoiceHelper voiceHelper=VoiceApplication.getInstance().getVoiceHelper();
		if(voiceHelper!=null&&voiceHelper.getDevice()!=null){
			phoneStr=phoneStr.replace("+86","");
			Intent intent=new Intent(this,CallOutActivity.class);
			//需要根据模式传递相应参数
			switch(mCallType){
			case VOIP_CALL_TYPE_DIRECT_TALK:
				//直播电话
				if(!phoneStr.startsWith("0")&&!phoneStr.startsWith("1")){
					//判断输入合法性
					VoiceApplication.getInstance().showToast(getString(R.string.network_dial_number_format));
					return;
				}
				intent.putExtra(VoiceApplication.VALUE_DIAL_VOIP_INPUT,phoneStr);
				intent.putExtra(VoiceApplication.VALUE_DIAL_MODE,VoiceApplication.VALUE_DIAL_MODE_DIRECT);
				startActivity(intent);
				break;
			case VOIP_CALL_TYPE_BACK_TALK:
		     	//回拨电话
				if(!phoneStr.startsWith("0")&&!phoneStr.startsWith("1")){
					//判断输入合法性
					VoiceApplication.getInstance().showToast(getString(R.string.network_dial_number_format));
					return;
				}
				if(CCPConfig.Src_phone==null||CCPConfig.Src_phone.equals("")){
					//判断本机号码是否正确
					VoiceApplication.getInstance().showToast(getString(R.string.src_phone_empty));
					return;
					
				}
				intent.putExtra(VoiceApplication.VALUE_DIAL_VOIP_INPUT,phoneStr);
				intent.putExtra(VoiceApplication.VALUE_DIAL_MODE, VoiceApplication.VALUE_DIAL_MODE_BACK);
				startActivity(intent);
				
			}
		}else{
			VoiceApplication.getInstance().showToast("尚未连接到云通讯，重新获得Device！");
			VoiceApplication va= VoiceApplication.getInstance();
			va.initVoiceHelper(helperHandler);
		}*/
		
	}
	String phoneto="";
	int tyoe=0;
	private Handler helperHandler=new Handler(){
		 @Override
		 public void handleMessage(Message msg){
			  startVoipCall(tyoe,phoneto);
		 }
	};
	
}
